/*
 * Copyright © 2024-2025 Wenze Wei
 *
 * This file is part of StadionOS.
 *
 * This Source Code Form is subject to the terms of the GNU General Public License, v. 2.0.
 * You can obtain a copy of the GPL at
 * https://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 * the specific language governing rights and limitations under the License.
 */

#include "../include/fsd.h"

/**
 * @brief Reads a directory entry.
 *
 * This function reads the next directory entry from 'dirp'.
 *
 * @param dirp The directory stream.
 * @return struct Tlinux_dirent* The directory entry, or NULL on error or end of directory.
 */
struct Tlinux_dirent *Sreaddir(TDIR *dirp) {
    int bytes = syscall(SYS_getdents, dirp->fd, dirp->buf, sizeof(dirp->buf));
    if (bytes <= 0) return NULL;

    struct Tlinux_dirent *entry;
    int offset = 0;

    while (offset < bytes) {
        entry = (struct Tlinux_dirent *)(dirp->buf + offset);
        offset += entry->d_reclen;
        if (entry->d_ino != 0) {
            return entry;
        }
    }

    return NULL;
}
